package com.hzqy.service.itf;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hzqy.persistence.dao.commons.CommonsDao;
import com.hzqy.persistence.dao.hqjc.HqjcDao;
import com.hzqy.persistence.dao.itf.YxtItfDao;
import com.hzqy.service.commons.OrgModelFilterService;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.CmCatalogVo;
import com.hzqy.web.vo.CmContentVo;
import com.hzqy.web.vo.PmsOrgVo;
import com.hzqy.web.vo.SysConfigVo;
import com.hzqy.web.vo.UserHistoryVo;
import com.hzqy.web.vo.YxtAcountInfoVo;
import com.hzqy.web.vo.YxtAlbumVo;
import com.hzqy.web.vo.YxtJiaoFuResVo;
import com.hzqy.web.vo.YxtLuBoResVo;
import com.hzqy.web.vo.YxtMsCollectVo;
import com.hzqy.web.vo.YxtMsMskcVo;
import com.hzqy.web.vo.YxtMsSpzxVo;
import com.hzqy.web.vo.YxtNmsykClassRoomCourseVo;
import com.hzqy.web.vo.YxtNmsykCourseVo;
import com.hzqy.web.vo.YxtNmsykLessonVo;
import com.hzqy.web.vo.YxtNmsykMenuVo;
import com.hzqy.web.vo.YxtNmsykTopTeacherVo;
import com.hzqy.web.vo.YxtSchoolVo;

@Service
public class YxtItfServiceBean extends OrgModelFilterService{
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	
	/**
	 * 默认用户进入时绑定的组织
	 */
	public static final int SESSION_PMS_ORG_IS_EMPTY_ORG_ID = 23;
	
	@Resource
	private YxtItfDao yxtDao;
	@Resource
	private CommonsDao commonsDao;
	@Resource
	private HqjcDao hqjcDao;
	
	public PmsOrgVo selectContentOrgList(String serverid,int f_ccc_catalogid){
		PmsOrgVo results = yxtDao.selectOrgOfContent(serverid,f_ccc_catalogid);
		return results;
	}
	public YxtAcountInfoVo isBindYxt(String serverId,String schoolName, int f_ccc_catalogid) {
		return yxtDao.selectYxtAccountInfo(serverId, schoolName,f_ccc_catalogid);
	}
	public List<YxtJiaoFuResVo> getYxtJiaoFuGrade(String schoolid,int f_ccc_catalogid) {
		return yxtDao.getYxtJiaoFuGrade(schoolid,f_ccc_catalogid);
	}
	public List<YxtJiaoFuResVo> getYxtJiaoFuCourse(String schoolid,String grade,int f_ccc_catalogid) {
		return yxtDao.getYxtJiaoFuCourse(schoolid,grade,f_ccc_catalogid);
	}
	public int getYxtJiaoFuResCount(String schoolid,String grade,String course,int f_ccc_catalogid) {
		return yxtDao.getYxtJiaoFuResCount(schoolid,grade,course,f_ccc_catalogid);
		
	}
	public List<YxtJiaoFuResVo> getYxtJiaoFuRes(String schoolid,String grade,String course,int f_ccc_catalogid,int pageNo,int pageSize) {
		return yxtDao.getYxtJiaoFuRes(schoolid,grade,course,f_ccc_catalogid,pageNo,pageSize);
	}
	
	public List<YxtLuBoResVo> getYxtLuBoResCourse(String schoolid,String classid,int f_ccc_catalogid) {
		return yxtDao.getYxtLuBoResCourse(schoolid,classid,f_ccc_catalogid);
	}
	public int getYxtLuBoResCount(String schoolid,String classid,String course,int f_ccc_catalogid) {
		return yxtDao.getYxtLuBoResCount(schoolid,classid,course,f_ccc_catalogid);
	}
	public List<YxtLuBoResVo> getYxtLuBoRes(String schoolid,String classid,String course,int f_ccc_catalogid,int pageNo,int pageSize) {
		return yxtDao.getYxtLuBoRes(schoolid,classid,course,f_ccc_catalogid,pageNo,pageSize);
	}
	public List<YxtLuBoResVo>  getYxtLuBoResClassList(String schoolid,int f_ccc_catalogid) {
		return yxtDao. getYxtLuBoResClassList(schoolid,f_ccc_catalogid);
	}
	
	public int getYxtAlbumResCount(String schoolid,String f_ya_albumtype,String f_ya_areacode,String f_ya_gradetype,String f_ya_gradeid,String f_ya_subjectid){
		return yxtDao.getYxtAlbumResCount(schoolid,f_ya_albumtype,f_ya_areacode,f_ya_gradetype,f_ya_gradeid,f_ya_subjectid);
	}
	
	public List<YxtAlbumVo> getYxtAlbumResList(String schoolid,String f_ya_albumtype,String f_ya_areacode,String f_ya_gradetype,String f_ya_gradeid,String f_ya_subjectid,int pageNo,int pageSize){
		return yxtDao.getYxtAlbumResList(schoolid,f_ya_albumtype,f_ya_areacode,f_ya_gradetype,f_ya_gradeid,f_ya_subjectid,pageNo,pageSize);
	}
	public int getYxtAlbumResContentCount(String schoolid,String f_yjr_albumlistid,String f_yjr_entry,int f_ccc_catalogid){
		return yxtDao.getYxtAlbumResContentCount(schoolid,f_yjr_albumlistid,f_yjr_entry,f_ccc_catalogid);
	}
	public List<YxtJiaoFuResVo> getYxtAlbumResContentList(String schoolid,String f_yjr_entry,String f_yjr_albumlistid,int f_ccc_catalogid,int pageNo,int pageSize){
		return yxtDao.getYxtAlbumResContentList(schoolid,f_yjr_albumlistid,f_yjr_entry,f_ccc_catalogid,pageNo,pageSize);
	}
	
	/**
	 * 为未创建的用户新建一条对应业务账号数据(同时自动绑定业务账号分类)
	 * 业务账号归属企业教育厅（id=22）绑定分类业务账号（18）
	 * 调用初始方法com.hzqy.web.filter.OrgModelFilter->91行 yxtItfService.insertContent(cmContentVo);
	 * @param cmContentVo 
	 * @return 录入结果
	 */
	public int insertContent(CmContentVo cmContentVo){
		return yxtDao.insertContent(cmContentVo);
	}

	public String selectAreaIdByServerId(String serverid){
		return commonsDao.selectAreaIdByServerId(serverid);
	}
	public PmsOrgVo selectOrgVo(int f_po_id) {
		return yxtDao.selectOrgVo(f_po_id);
	}
	public List<YxtAlbumVo> getYxtAlbumGradeType(String schoolid,
			String f_ya_albumtype, String f_ya_areacode) {
		return yxtDao.getYxtAlbumGradeType(schoolid,f_ya_albumtype,f_ya_areacode);
	}
	public List<YxtAlbumVo> getYxtAlbumGradeId(String schoolid,
			String f_ya_albumtype, String f_ya_areacode, String f_ya_gradetype) {
		return yxtDao.getYxtAlbumGradeId(schoolid,f_ya_albumtype,f_ya_areacode,f_ya_gradetype);
	}
	public List<YxtAlbumVo> getYxtAlbumSubjectId(String schoolid,
			String f_ya_albumtype, String f_ya_areacode, String f_ya_gradetype,
			String f_ya_gradeid) {
		return yxtDao.getYxtAlbumSubjectId(schoolid,f_ya_albumtype,f_ya_areacode,f_ya_gradetype,f_ya_gradeid);
	}
	public List<CmContentVo> selectNoticeList(String userId, int f_catalog_id,
			int f_po_id,int f_ym_type, int pageNo, int pageSize) {
		return yxtDao.selectNoticeList(userId,f_catalog_id,f_po_id,f_ym_type, pageNo, pageSize);
	}
	public int selectNoticeListCount(String userId,
			int f_catalog_id, int f_po_id,int f_ym_type) {
		return yxtDao.selectNoticeListCount(userId,f_catalog_id,f_po_id,f_ym_type);
	}
	public List<CmContentVo> selectSmsList(String userId, int f_catalog_id,int f_ym_type,int pageNo,int pageSize) {
		return yxtDao.selectSmsList(userId,f_catalog_id,f_ym_type, pageNo, pageSize);
	}
	public int selectSmsListCount(String userId, int f_catalog_id, int f_ym_type) {
		return yxtDao.selectSmsListCount(userId,f_catalog_id,f_ym_type);
	}
	public YxtSchoolVo selectYxtSchoolInfo(String schoolid) {
		return yxtDao.selectYxtSchoolInfo(schoolid);
	}
	public int selectCatalogInfoListByParentCatalogIdCount(int f_catalog_id) {
		int results = yxtDao.selectCatalogInfoListByParentCatalogIdCount(f_catalog_id);
		return results;
	}
	public List<CmCatalogVo> selectCatalogInfoListByParentCatalogId(int f_catalog_id,int pageNo,int pageSize) {
		List<CmCatalogVo> results = yxtDao.selectCatalogInfoListByParentCatalogId(f_catalog_id, pageNo, pageSize);
		return results;
	}
	public Map<String, String> updatePmsOrgDesc(PmsOrgVo orgVo) {
		Map<String,String> map = new HashMap<String, String>();
		int flag =yxtDao.updatePmsOrgDesc(orgVo);
		if(flag>0){
			map.put("flag", flag+"");
			map.put("message", "更新成功");
		}else{
			map.put("flag", flag+"");
			map.put("message", "更新失败");
		}
		return map;
	}
	
	@Override
	public void handleEvent(int Event, Map<String, Object> param) {
		HttpServletRequest request = ((HttpServletRequest)param.get("request"));
		HttpServletResponse response = ((HttpServletResponse)param.get("response"));
		HttpSession session = request.getSession();
		String serverid = (String) param.get("serverId");
		PmsOrgVo orgVo = (PmsOrgVo) session.getAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO);
		String gxh_params=request.getParameter("gxh_params");//个性化验证
		String gxh_companyid=request.getParameter("gxh_companyid");//个性化企业id
		try {
			switch (Event) {
			case SESSION_PMS_ORG_IS_EMPTY:
				break;
			case PMS_ORG_OF_SERVERID_NOT_FOUND:
				//为查询到业务账号绑定的模板信息新增一份模板信息
				//需要插入content表的api插入同时需要绑定业务账号（18）分类默认企业为教育厅（）
				LOG.debug("未查询到模板数据新增用户："+serverid+"至教育厅下");
				String cityId=this.selectAreaIdByServerId(serverid);
				//int companytId=getCityOrg(cityId);
				int companytId = SESSION_PMS_ORG_IS_EMPTY_ORG_ID;
				//个性化企业id调整
				if(gxh_params!=null&&gxh_companyid!=null&&gxh_params.indexOf("gxh")>=0){
					try{
						companytId=Integer.parseInt(gxh_companyid);//桐乡ID
						 //为新用户添加重定向地址,用于获取模板地址
						param.put("redirect_url", request.getContextPath()+"/index/index_school.jsp");
					}catch(NumberFormatException e){
						LOG.error("个性化企业id赋值失败"+serverid,e);
					}
				}
				CmContentVo cmContentVo=new CmContentVo();
				//需要更新业务账号判断是哪个地市
				cmContentVo.setF_cc_name(serverid);
				cmContentVo.setF_cc_offlinedate("2051-01-01 01:00:00");
				cmContentVo.setF_cc_onlinedate("2016-01-01 01:00:00");
				cmContentVo.setF_cc_type(100);
				cmContentVo.setF_cco_orgId(companytId+"");
				this.insertContent(cmContentVo);
				if(companytId!=SESSION_PMS_ORG_IS_EMPTY_ORG_ID){// 客户被修改
					orgVo=yxtDao.selectOrgVo(companytId);
					if(orgVo!=null&&orgVo.getF_po_model() > 0){
						session.setAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO, orgVo);
						CmContentVo contentVo = new CmContentVo();
						contentVo.setF_cc_cprid("5");
						contentVo.setF_cc_id(orgVo.getF_po_model());
						contentVo=hqjcDao.selectContent(contentVo);
						if(contentVo != null){//获取企业绑定模板路径
							String modelPath=contentVo.getF_cc_desc().replaceAll("<([^>]*)>","");
							orgVo.setF_po_model_url(modelPath);
						}else{
							LOG.error("无法获取id=" + orgVo.getF_po_model() + "的模版内容 业务账号="+param.get("serverId"));
							handleEvent(OrgModelFilterService.MODEL_NOT_FOUND, param);
						}
					}else{
						LOG.error("组织=" + orgVo.getF_po_name() + " 未选择模版！");
					}
				}
				
				break;
			case PMS_ORG_OF_SERVERID_FOUND:
				//存在学校数据然后需要判断是否为翼校通数据
				YxtAcountInfoVo accountInfoVo=this.isBindYxt(serverid, orgVo.getF_po_name(), getCatalogidOfServerid());//这里定义业务账号必须绑定目录ID为18的分类
				if(accountInfoVo!=null){//获取翼校通数据并存储至session
					LOG.debug("获取到翼校通账号信息SESSION_USER_YXT_INFO:"+accountInfoVo.getF_yai_username());
					session.setAttribute(SessionKey.SESSION_USER_YXT_INFO, accountInfoVo);
				}else{
					LOG.debug("未查询到翼校通用户信息");
				}
				break;
			case MODEL_NOT_FOUND:
				orgVo.setF_po_model_url("/school_hd/commons_model/tianyi_study/index_study.jsp");
				break;
			case USER_PMS_ORG_MODEL_FOUND:
				if(gxh_params!=null&&gxh_companyid!=null&&gxh_params.indexOf("gxh")>=0){//登入成功
					try{
						companytId=Integer.parseInt(gxh_companyid);//企业id
						PmsOrgVo orgVo_=yxtDao.selectOrgVo(companytId);
						if(orgVo!=null&&orgVo_.getF_po_model() > 0){
							CmContentVo contentVo = new CmContentVo();
							contentVo.setF_cc_cprid("5");
							contentVo.setF_cc_id(orgVo_.getF_po_model());
							contentVo=hqjcDao.selectContent(contentVo);
							if(contentVo != null){//获取企业绑定模板路径
								String modelPath=contentVo.getF_cc_desc().replaceAll("<([^>]*)>","");
								orgVo.setF_po_model_url(modelPath);
							}
						}else{
							LOG.error("组织=" + orgVo_.getF_po_name() + " 未选择模版！");
						}
					}catch(NumberFormatException e){
						LOG.error("个性化企业id赋值失败"+serverid,e);
					}
				}
				break;
			case USER_PMS_ORG_MODEL_NOT_FOUND:
				//到时需要区分高标清，暂时先统一定向到高清学校目录，未考虑酒店行业应用情况，需要后期考虑，注意！！！！！。
				String url= url=request.getContextPath()+"/school_hd/commons_model/tianyi_study/index_study.jsp";
				if(param.get("redirect_url")!=null){//是否存在重定向地址
					url=param.get("redirect_url").toString();
				}
				response.sendRedirect(url); //重定向到用户未绑定模板页面
				return;
			default:
				break;
			}
			
		} catch (Exception e) {
			LOG.error("", e);
		}
		
	}

	@Override
	public int getCatalogidOfServerid() {
		return 18;
	}
	
	/**
	 * 通过地市id获取地市对应企业
	 * @param cityId
	 * @return
	 */
	public int getCityOrg(String cityId){
		int orgId=6523;
		int flagId=571;
		try{
			flagId=Integer.parseInt(cityId);
		}catch(NumberFormatException e){
			LOG.error("转换区号错误：请检查"+e);
		}
		switch(flagId){
			case  570:
				orgId=6688;//衢州
			break;
			case  571:
				orgId=6523;//杭州
				break;
			case  572:
				orgId=6687;//湖州
				break;
			case  573:
				orgId=6686;//嘉兴
				break;
			case  574:
				orgId=6690;//宁波
				break;
			case  575:
				orgId=6692;//绍兴
				break;
			case  576:
				orgId=6695;//台州
				break;
			case  577:
				orgId=6691;//温州
				break;
			case  578:
				orgId=6694;//丽水
				break;
			case  579:
				orgId=6693;//金华
				break;
			case  580:
				orgId=6696;//舟山
				break;
		}
		return orgId;
	}
	
	
	public List<YxtMsSpzxVo> selectAllSpzx(String stage, String course, int pageNo, int pageSize) {
		List<YxtMsSpzxVo> list =  yxtDao.selectAllSpzx(stage,course,pageNo,pageSize);
		return list;
	}
	public List<YxtMsMskcVo> selectAllMskc(int pageNo, int pageSize) {
		List<YxtMsMskcVo> list = yxtDao.selectAllMskc(pageNo,pageSize);
		return list;
	}
	public List<YxtMsSpzxVo> selectCoursefromStage(String stage) {
		List<YxtMsSpzxVo> list = yxtDao.selectCoursefromStage(stage);
		return list;
	}
	public List<YxtMsMskcVo> getContentForMskc(String f_ykc_courseid, int pageNo, int pageSize) {
		List<YxtMsMskcVo> list =  yxtDao.getContentForMskc(f_ykc_courseid,pageNo,pageSize);
		return list;
	}
	public YxtMsSpzxVo selectMsSpzxformId(int f_yms_id) {
		YxtMsSpzxVo spzxVo = yxtDao.selectMsSpzxformId(f_yms_id);
		return spzxVo;
	}
	public int insertCollectByAlbum(YxtMsCollectVo collectVo) {
		int flag = yxtDao.insertCollectByAlbum(collectVo);
		return flag;
	}
	
	public List<UserHistoryVo> selectPlayRecord(UserHistoryVo userHistoryVo) {
		List<UserHistoryVo> historyVoList = yxtDao.selectPlayRecord(userHistoryVo);
		return historyVoList;
	}
	public List<YxtMsCollectVo> selectCollect(String f_ysc_user_id) {
		List<YxtMsCollectVo> collectVo = yxtDao.selectCollect(f_ysc_user_id);
		return collectVo;
	}
	public void deleteMsykAlbum(YxtMsCollectVo collectVo) {
		yxtDao.deleteMsykAlbum(collectVo);
		
	}
	public List<YxtNmsykMenuVo> selectNmsykMenu(YxtNmsykMenuVo menuVo) {
		List<YxtNmsykMenuVo> vos = yxtDao.selectNmsykMenu(menuVo);
		for(int i=0;i<vos.size();i++){//将返回结果进行删选；删除不需要的数据
			if(vos.get(i).getF_ynm_stage().equals("全部")){
				vos.remove(vos.get(i));
			}
		}
		return vos;
	}
	public List<YxtNmsykLessonVo> selectLseeonFromId(YxtNmsykCourseVo courseVo) {
		return yxtDao.selectLseeonFromId(courseVo);
	}
	public YxtNmsykCourseVo selectCourseById(YxtNmsykCourseVo courseVo) {
		return yxtDao.selectCourseById(courseVo);
	}
	public SysConfigVo selectSysByKey(String string) {
		return yxtDao.selectSysByKey(string);
	}
	public int insertMsykContent(CmContentVo cmContentVo) {
		return yxtDao.insertMsykContent(cmContentVo);
	}
	public YxtNmsykLessonVo selectLseeonByContentId(YxtNmsykCourseVo courseVo) {
		return yxtDao.selectLseeonByContentId(courseVo);
	}
	public CmContentVo selectContentbyId(String f_ynl_old_id) {
		return yxtDao.selectContentbyId(f_ynl_old_id);
	}
	public YxtNmsykCourseVo selectCourseByContent(String f_ynl_content_id) {
		return yxtDao.selectCourseByContent(f_ynl_content_id);
	}
	public List<YxtNmsykCourseVo> selectCourse(YxtNmsykCourseVo courseVo) {
		return yxtDao.selectCourse(courseVo);
	}
	public List<YxtNmsykCourseVo> selectCourseBySearch(YxtNmsykCourseVo courseVo) {
		List<YxtNmsykCourseVo> courseVos= yxtDao.selectCourseBySearch(courseVo);
		return courseVos;
	}
	public List<YxtNmsykTopTeacherVo> selectTopTeacher(YxtNmsykTopTeacherVo yxtNmsykTopTeacherVo) {
		List<YxtNmsykTopTeacherVo> teacherVos = yxtDao.selectTopTeacher(yxtNmsykTopTeacherVo);
		return teacherVos;
	}
	
	public int selectNotViewedCount(String f_nmcr_user_phone,String f_nmcc_filetype,String f_uvh_serverid,String riqi){
		int count = yxtDao.selectNotViewedCount(f_nmcr_user_phone,f_nmcc_filetype,f_uvh_serverid,riqi);
		return count;
	}
	public List<YxtNmsykClassRoomCourseVo> selectLLClassRoom(String f_yai_phone, String f_nmcc_subject, String f_nmcc_filetype, int page,
			int rows) {
		List<YxtNmsykClassRoomCourseVo> classRoomCourseVos = yxtDao.selectLLClassRoom(f_yai_phone,f_nmcc_subject,f_nmcc_filetype,page,rows);
		return classRoomCourseVos;
	}
	public CmContentVo selectContentByContentId(CmContentVo cmContentVo) {
		CmContentVo contentVo = yxtDao.selectContentByContentId(cmContentVo);
		return contentVo;
	}
}
